package com.hgkj.common.async.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池
 */
@Configuration
public class ThreadPoolConfig {

    @Value("${async.threadPool.namePrefix}")
    private String namePrefix;

    @Value("${async.threadPool.coreSize}")
    private int coreSize;

    @Value("${async.threadPool.maxSize}")
    private int maxSize;

    @Value("${async.threadPool.queueCapacity}")
    private int queueCapacity;

    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(coreSize);  // 核心线程数
        executor.setMaxPoolSize(maxSize);  // 最大线程数
        executor.setQueueCapacity(queueCapacity); // 队列容量
        executor.setThreadNamePrefix(namePrefix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
